/*
Copyright ? 2020 ChenYanan.

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

     http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
*/
#include "cynos_cfg.h"
#include "cynos_fifo.h"

#if USE_CYNOS_FIFO

/*pop*/
CYNOS_STATUS fifo_pop(CynOS_FIFO * fifo_handle,CynOS_VOID *data)
{	
	CynOS_U8 _fifo_step = fifo_handle->fifo_member_size;

	if(fifo_handle->fifo_staus.fifo_r != fifo_handle->fifo_staus.fifo_w)
	{
		if((fifo_handle->fifo_staus.fifo_r + 1) >= fifo_handle->fifo_deep)
		{
			fifo_handle->fifo_staus.fifo_r = 0;
		}
		else
		{
			fifo_handle->fifo_staus.fifo_r++;
		}
		memcpy(data,fifo_handle->fifo[fifo_handle->fifo_staus.fifo_r * _fifo_step],_fifo_step);
		return CYNOS_OK;
	}
	return CYNOS_ERR;
}
/*push*/
CYNOS_STATUS fifo_push(CynOS_FIFO * fifo_handle,CynOS_VOID *data)
{	
	CynOS_U8 _fifo_step = fifo_handle->fifo_member_size;
	CynOS_U16 _nw_index;

	if((fifo_handle->fifo_staus.fifo_w + 1) >= fifo_handle->fifo_deep)
	{
		_nw_index = 0;
	}
	else
	{	
		_nw_index = fifo_handle->fifo_staus.fifo_w + 1;
	}

	if(fifo_handle->fifo_staus.fifo_r == _nw_index)
	{
		//fifo full
		return CYNOS_ERR;
	}

	memcpy(fifo_handle->fifo[fifo_handle->fifo_staus.fifo_w * _fifo_step],data,_fifo_step);
	fifo_handle->fifo_staus.fifo_w = _nw_index;
	return CYNOS_OK;

}
/*get the data size*/
CYNOS_STATUS fifo_size(CynOS_U8 *fifo,CynOS_U16 *size)
{	
	//TODO
	return CYNOS_OK;
}

/*fifo class init*/
void CynOS_FIFO_Init(CynOS_FIFO * fifo_handle,CynOS_U8 member_size,CynOS_U16 cache_size,CynOS_VOID *cache)
{
	if(fifo_handle && (member_size > 0))
	{
		memset(fifo_handle,0,sizeof(CynOS_FIFO));
		fifo_handle->pop=fifo_pop;
		fifo_handle->push=fifo_push;
		fifo_handle->size=fifo_size;

		fifo_handle->fifo_member_size = member_size;
		fifo_handle->fifo_deep = cache_size/member_size;
		fifo_handle->fifo = (CynOS_U8 *)cache;
		return CYNOS_OK;
	}
	return CYNOS_ERR;	
}




#endif


